package com.gitee.wsl.scheduler

import com.gitee.wsl.concurrent.api.SuspendRunnable
import com.gitee.wsl.ext.K
import com.gitee.wsl.ext.runBlocking
import com.gitee.wsl.scheduler.queue.ITagTask
import com.gitee.wsl.scheduler.queue.TaskQueue
import com.gitee.wsl.scheduler.queue.TaskQueueImp

/**
 * # AbstractScheduler
 *
 * AbstractScheduler is an abstract base class that provides common functionality for different
 * scheduler implementations.
 * It manages the registration and cancellation of tasks using a
 * thread-safe map and provides unique task IDs.
 *
 * This class implements the [TaskScheduler] interface and provides base implementations for
 * managing tasks.
 * Subclasses are responsible for implementing the task scheduling methods.
 */
abstract class AbstractTaskScheduler(
    override val taskRepository: TaskRepository = MemoryTaskRepository.DEFAULT
): TaskScheduler {

    /**
     * A thread-safe map that holds all the registered tasks with their unique IDs.
     */

    // We assume that schedulers can use different threads to run tasks,
    // so we need to make thread-safe incrementation.
     //@OptIn(ExperimentalAtomicApi::class)
     //var tasksWas = atomic(0)

     val queue: TaskQueue by lazy { TaskQueueImp(this) }

    inner class QTask(val id:Int,val task: SuspendRunnable): ITagTask {
        override fun tag(): String  = id.toString()

        override suspend fun await(): Boolean = queue.taskManager.hasTak(tag())

        override suspend fun execute() = task()

    }

    override fun queueTask(task: SuspendRunnable): ITagTask {
        return QTask(nextId(),task).apply { K.runBlocking { queue.enqueue(this@apply)}}
    }


}